package com.kandroid.demo.cameratest

import android.app.Activity
import android.hardware.Camera
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.Surface
import android.view.SurfaceHolder
import android.view.SurfaceView

class MainActivity : AppCompatActivity(), SurfaceHolder.Callback {

    private lateinit var surfaceView: SurfaceView
    private var camera: Camera? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        surfaceView = findViewById(R.id.surfaceView)

        val surfaceHolder = surfaceView.holder
        surfaceHolder.addCallback(this)
    }

    override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {
        val aspect = width.toDouble() / height
    }

    override fun surfaceDestroyed(holder: SurfaceHolder?) {

    }

    override fun surfaceCreated(holder: SurfaceHolder?) {
        camera = openCamera()
        camera?.apply {
            val params = this.parameters
            val previewSize = params.supportedPreviewSizes[0]
            params.setPreviewSize(previewSize.width, previewSize.height)
            val orientation = getOrientation(Camera.CameraInfo.CAMERA_FACING_BACK, windowManager.defaultDisplay.rotation)
            this.setDisplayOrientation(orientation)
            this.startPreview()
        }
    }

    private fun openCamera(): Camera? {
        val camera = Camera.open()
        camera?.apply {
            try {
                this.setPreviewDisplay(surfaceView.holder)
            } catch (e: Exception) {
            }
        }
        return camera
    }

    private fun getOrientation(cameraId: Int, rotation: Int): Int {
        val info = Camera.CameraInfo()
        Camera.getCameraInfo(cameraId, info)
        val degrees = when (rotation) {
            Surface.ROTATION_0 ->  0
            Surface.ROTATION_90 -> 90
            Surface.ROTATION_180 -> 180
            Surface.ROTATION_270 -> 270
            else -> 0
        }
        var result: Int
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360
            result = (360 - result) % 360  //前置摄像头360镜面对称
        } else {  //后置摄像头
            result = (info.orientation - degrees + 360) % 360
        }
        return result
    }
}
